`
You should see similar output.
Loops and Loop Controls
Like many programming languages, bash lets you repeat chunks of code using
loops. Loops can be particularly useful in your penetration testing adventures
because they can help you accomplish tasks such as the following:
•
Continuously checking whether an IP address is online after a reboot; once the
IP address is detected, stop checking.
•
Iterating through a list of hostnames, for example to run a specific exploit
against each of them or determine whether there is a firewall protecting them.
•
Testing for a certain condition and then running a loop when it is met. For
example, checking whether a host is online, and if so, performing a brute force
attack against it.
The following sections introduce you to the three kinds of loops in bash,
while, until, and for, as well as the break and continue statements for
working with loops.
while
In bash, while loops allow you to run a code block until some test returns a
successful exit status code. You might use them in penetration testing to
continuously perform a port scan on a network and pick up any new hosts that join
the network, for example.
Listing 2-10 shows the syntax of a while loop.
while some_condition; do
# run commands while the condition is true
done
Listing 2-10
A while loop
A while loop starts with the keyword while, followed by an expression
that describes the condition. We then surround the code to be executed with the do
and done keywords, which define the start and end of the code block.
You can use while loops to run some chunk of code infinitely by using
true as the condition; because true always returns a successful exit code, the
code will always run. Let’s use a while loop to repeatedly print a command to
the screen. Save this script to a file named basic_while.sh and run it.
#!/bin/bash
while true; do
echo "Looping..."
sleep 2
done
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks